<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix='sec' uri='http://www.springframework.org/security/tags'%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<script type="text/javascript" src="scripts/boot.js"></script>
	
	<style type="text/css">
	    .errorText
	    {
	        color:red;
	    }
	    .Delete_Button
        {
            font-size:11px;color:#1B3F91;font-family:Verdana;  
            margin-right:5px;          
        }
    </style>
</head>
<body>
	<fieldset style="border:solid 1px #aaa;padding:3px;">
		<legend >订单基本信息（系统允许客户网退、退单数量是<span id="back_count"></span>个）</legend>
		<form id="form1" method="post">
			<input class="mini-hidden" name="customerId" id="customer_id"/>
	        <table cellspacing="10" cellpadding="0">
	        	<tr>
	        		<td style="width:100px;" align="right">
	        			收货人：
	        		</td>
	        		<td colspan="4">
	        			<input requiredErrorText="收货人不能为空" name="name" style="width: 130px;" class="mini-textbox" required="true" vtype="maxLength:7"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			联系电话1：
	        		</td>
	        		<td colspan="2">
	        			<input name="contactNo" style="width: 130px;" class="mini-textbox" required="true" vtype="int; maxLength:12; numType"/>
	        			<sec:authorize url='/orders_add_outgoing.do'>
	        			<a class="mini-button" iconCls="icon-outgoing" onclick="outgoing1">外呼</a>
	        			</sec:authorize>
	        		</td>
	        		<td colspan="2" style="width:310px;" align="right">
	        			<span>联系电话2：</span>
	        			<input name="contactNos" emptyText="请输入联系电话2" style="width: 130px;" class="mini-textbox" vtype="int; maxLength:12; numType"/>
	        			<sec:authorize url='/orders_add_outgoing.do'>
	        			<a class="mini-button" iconCls="icon-outgoing" onclick="outgoing2">外呼</a>
	        			</sec:authorize>
	        		</td>
	        	</tr>
	        	<div id="win—outgoing" class="mini-window" showModal="false" allowDrag="false" showHeader="false" title="呼出" style="width: 200px;height: 110px;">
				    <input labelField="true" label="号码：" labelStyle="width: 40px;" class="mini-textbox" style="width:170px;margin-top: 7px;margin-left: 5px;" id="outNumId" enabled="false"/> 
				    <input labelField="true" label="加拨：" labelStyle="width: 40px;" class="mini-combobox" style="width:170px;margin-top: 7px;margin-left: 5px;" id="addNum"
				    	url="dictionary_cm_key_val_view.do?typeName=CALL_ADD_TYPE" textField="keyValue" valueField="keyValue" showNullItem="true" nullItemText="无"/> 
					<div style="text-align:center;padding-bottom: 5px;margin-top: 10px;">
						<a class="mini-button" onclick="outgoingOk" style="">呼出</a>
						<a class="mini-button" onclick="onClose2" style="margin-left: 30px;">关闭</a>
					</div>
				</div>
	        	<tr>
	        		<td align="right">
	        			地址：
	        		</td>
	        		<td colspan="4">
	        			<input  name="provinceId" id="province_val" class="mini-hidden"/>
			      		<input style="width: 130px;" id="province" name="pName" class="mini-textbox" required="true" onfocus="focusP" emptyText="请选择省份"/>
			      		<input name="cityId" class="mini-hidden" id="city_val" />
			      		<input class="mini-textbox" id="city" name="cName" style="width: 130px;" required="true" readOnly="true" emptyText="请选择城市"/>
			      		<input name="districtId" id="district_val" class="mini-hidden"/>
			      		<input class="mini-textbox" id="district" name="dName" style="width: 80px;" required="true" readOnly="true" emptyText="请选择区县"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			详细地址：
	        		</td>
	        		<td colspan="2">
	        			<input name="address" class="mini-textbox" style="width:265px;" required="true"/>
	        		</td>
	        		<td style="width:90px;" align="right">
	      				邮编：
	        		</td>
	        		<td>
	      				<input class="mini-textbox" emptyText="请输入邮编" name="zipCode" style="width: 130px;"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			备注：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" emptyText="请输入备注" name="ordersRemark" style="width: 524px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			是否开发票：
	        		</td>
	        		<td colspan="2">
	        			<input name="invoice" emptyText="请选择..." showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	               			url="dictionary_om_key_val_view.do?typeName=ORDER_INVOICE_TYPE" value="11"/>
	        		</td>
	        		<td align="right">
	        			媒体：
	        		</td>
	        		<td>
	        			<input name="mediaId" showNullItem="true" nullItemText="全部" emptyText="请选择..." style="width: 130px;" class="mini-combobox" valueField="id" textField="name"
	               			url="orders_find_media.do" required="true"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			订单性质：
	        		</td>
	        		<td colspan="2">
	        			<input name="nature" emptyText="请选择..." showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	              			url="dictionary_om_key_val_view.do?typeName=ORDER_NATURE_TYPE" value="12"
	              			<sec:authorize url="/dictionary_om_key_val_view_read.do">enabled="true"</sec:authorize> enabled="false"/>
	        		</td>
	        		<td align="right">
	        			物流公司：
	        		</td>
	        		<td>
	        			<input name="expressId" showNullItem="true" nullItemText="全部" emptyText="请选择..." style="width: 130px;" class="mini-combobox" valueField="id" textField="name"
	               			url="orders_find_logistics.do" showNullItem="true" nullItemText="无"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			支付方式：
	        		</td>
	        		<td colspan="2">
	        			<input name="payType" showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="keyName" required="true" textField="keyValue"
	               			url="dictionary_om_key_val_view.do?typeName=ORDER_PAY_TYPE" value="16"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			货款：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="payment" style="width: 70px;" enabled="false" value="0" id="orders_payment"/>
	        			<span style="margin-left: 84px;">运费：</span>
	        			<input class="mini-textbox" emptyText="请输入运费" name="freight" id="orders_freight" onvaluechanged="freightChange();" vtype="float;maxLength:11;negative" style="width: 70px;" value="0"
	        			<sec:authorize url="/orders_freight_read.do">enabled="true"</sec:authorize> enabled="false"/>
	        			<span style="margin-left: 60px;">应收金额：</span>
	        			<input class="mini-textbox" name="receivable" id="orders_receivable" onvaluechanged="receivableChange();" onfocus="getReceivable();" vtype="float;maxLength:11;negative" required="true" style="width: 70px;margin-left: 5px;" value="0"
	        			<sec:authorize url="/receivable_read.do">enabled="true"</sec:authorize> enabled="false"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right" >
	        			实收金额：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="amountPaid" id="amount_paid" vtype="float;maxLength:11;negative" onvaluechanged="amountPaidChange();" style="width: 70px;" required="true" value="0"
	        			<sec:authorize url="/amount_paid_read.do">enabled="true"</sec:authorize> enabled="false"/>
	        			<span style="margin-left: 60px;">使用余额：</span>
	        			<input class="mini-textbox" name="useMoney" id="use_money" style="width: 70px;" value="0" enabled="false"/>
	        			<span style="margin-left: 60px;">剩余金额：</span>
	        			<input class="mini-textbox" name="money" id="customer_money" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			本单使用积分：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="usePoints" required="true" id="orders_use_points" value="0" vtype="int;maxLength:11" style="width: 70px;" enabled="false"/>
	        			<span style="margin-left: 60px;">本单积分：</span>
	        			<input class="mini-textbox" name="points" id="orders_points" enabled="false" value="0" style="width: 70px;" />
	        			<span style="margin-left: 60px;">剩余积分：</span>
	        			<input class="mini-textbox" name="integral" id="customer_integral" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right" >
	        			本单使用红包：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="useRed" id="orders_use_red" required="true" vtype="int;maxLength:11" value="0" style="width: 70px;" enabled="false"/>
	        			<span style="margin-left: 60px;">本单红包：</span>
	        			<input class="mini-textbox" name="red" style="width: 70px;" required="true" onfocus="getRed();" vtype="int;maxLength:11;negative" value="0" id="red" onvaluechanged="redChange();"/>
	        			<span style="margin-left: 60px;">剩余红包：</span>
	        			<input class="mini-textbox" name="redEnvelopes" id="customer_redEnvelopes" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			客户级别变化：
	        		</td>
	        		<td colspan="4">
	        			<span id="keyCustomerLevel"></span>-------
	        			<input id="customer_level" showNullItem="true" nullItemText="全部" emptyText="请选择..." style="width: 138px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	               			url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_LEVEL_TYPE" value="1" onvaluechanged="levelChanged();"/>
	        		</td>
	        	</tr>
	        </table>
	        <div style="text-align:center;padding:10px;">     
	        	<sec:authorize url='/orders_edit_save.do'>          
	            <a class="mini-button" onclick="onOk" style="width:150px;">保存订单信息</a> 
	            </sec:authorize>      
	        </div>        
	    </form>
	    <div id="win1" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win2" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win3" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
	</fieldset>
	<fieldset style="border:solid 1px #aaa;padding:3px;">
		<legend >订单产品信息</legend>
		<div id="datagrid1" class="mini-datagrid" style="width:800px;height:auto;" showPager="false" allowResize="false" url="orders_product_view.do" idField="id">
	        <div property="columns">
	            <div field="medicineName" width="15%" headerAlign="center" align="center">名称</div>                
	            <div field="price" width="5%" align="center" headerAlign="center">价格</div>
	            <div field="prePrice" width="6%" headerAlign="center" align="center">优惠价格</div>            
	            <div field="quantity" width="5%" align="center" headerAlign="center">数量</div>            
	            <div field="freight" width="5%" headerAlign="center" align="center">运费</div>
	            <div field="usePoints" width="6%" headerAlign="center" align="center">积分抵扣</div>                
	            <div field="useRed" width="6%" headerAlign="center" align="center">红包抵扣</div>                
	            <div field="totalPrice" width="6%" headerAlign="center" align="center">实际价格</div>                
	            <div field="discountPrice" width="6%" headerAlign="center" align="center">折扣价格</div>                
	            <div field="premiums" width="4%" headerAlign="center" align="center">赠品</div>           
	            <div field="ridePin" width="4%" headerAlign="center" align="center">搭销</div>
	            <sec:authorize url='/orders_product_del.do'>       
	            <div name="action" width="5%" headerAlign="center" align="center" renderer="onActionRenderer" cellStyle="padding:0;">操作</div>
	            </sec:authorize>
	        </div>
    	</div>    
        <input class="mini-hidden" name="ordersId" id="orders_id"/>
		<div id="form2">
            <input class="mini-hidden" name="id"/>
            <table cellspacing="10" cellpadding="0">
                <tr>
                    <td style="width:130px;" align="right">药品：</td>
                    <td style="width:230px;">
                    	<input name="medicineId" emptyText="请选择..." style="width: 150px;" required="true" class="mini-buttonedit" allowInput="false" onbuttonclick="onButtonEdit"/>
                    </td>
                    <input class="mini-hidden" id="inventory"/>
                	<td style="width:130px;" align="right">数量：</td>
                	<td>
                		<input name="quantity" style="width: 60px;" required="true" class="mini-textbox" value="1" vtype="int;maxLength:11;negative"/>
                	</td>
                </tr>
                <tr>
                	<td align="right">价格：</td>
                	<td>
                		<input name="price" id="price" style="width: 60px;" class="mini-textbox" enabled="false" value="0"/>
                		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;优惠价格：
                		<input name="prePrice" id="pre_price" required="true" style="width: 60px;" vtype="float;maxLength:11;negative" class="mini-textbox" value="0"
                		<sec:authorize url="/pre_price_read.do">enabled="true"</sec:authorize> enabled="false"/>
                	</td>
                	<td align="right">运费：</td>
                	<td>
                		<input name="freight" style="width: 60px;" required="true" vtype="float;maxLength:11;negative" class="mini-textbox" minValue="0" value="0" />
                	</td>
                </tr>
                <tr>
                	<td align="right">积分抵扣：</td>
                	<td>
                		<input name="usePoints" id="use_points" style="width: 60px;" required="true" class="mini-textbox" onvaluechanged="usePointsValid" value="0" vtype="int;maxLength:11;negative"/>
                		<span id="use_points_error" class="errorText"></span>
                	</td>
                	<td align="right">红包抵扣：</td>
                	<td>
                		<input name="useRed" id="use_red" style="width: 60px;" required="true" class="mini-textbox" onvaluechanged="useRedValid" value="0" vtype="int;maxLength:11;negative"/>
                		<span id="use_red_error" class="errorText"></span>
                	</td>
                </tr>
            </table>
        </div>
		<div style="text-align:center;padding:10px;">               
			<sec:authorize url='/orders_product_save.do'>
		    <a class="mini-button" onclick="onOk2" style="width:150px;">保存产品信息</a>     
		    </sec:authorize>  
	    </div>
	</fieldset>
	<div style="text-align:center;padding:10px;">   
        <sec:authorize url='/orders_edit_status.do'>
	    <a class="mini-button" onclick="onOk3" style="width:150px;">订单生效</a>  
	    </sec:authorize>
	    <a class="mini-button" onclick="onCancel" style="width:150px; margin-left: 20px;">关闭</a>     
    </div>
</body>
</html>

<script type="text/javascript">
	mini.parse();
	var form1 = new mini.Form("form1");
	
	var media = mini.getbyName("mediaId");
	var nature = mini.getbyName("nature");
	
	var consignee = mini.getbyName("name");
	var contactNo = mini.getbyName("contactNo");
	var contactNos = mini.getbyName("contactNos");
	var address = mini.getbyName("address");
	var zipCode = mini.getbyName("zipCode");
	var customerMoney = mini.get("customer_money");
	var customerIntegral = mini.get("customer_integral");
	var customerRedEnvelopes = mini.get("customer_redEnvelopes");
	function SetData(data) {
		data = mini.clone(data);
		$.post("customer_find_info.do", {id: data.cId}, function(data){
			consignee.setValue(data.customer.name);
			contactNo.setValue(data.customer.contactNo);
			contactNos.setValue(data.customer.contactNos);
			provinceVal.setValue(data.customer.provinceId);
			province.setValue(data.customer.pName);
			cityVal.setValue(data.customer.cityId);
			city.setValue(data.customer.cName);
			districtVal.setValue(data.customer.districtId);
			district.setValue(data.customer.dName);
			address.setValue(data.customer.address);
			zipCode.setValue(data.customer.zipCode);
			if(null != data.customer.ordersNature) {
				nature.setValue(data.customer.ordersNature);
			}
			if(null != data.customer.media) {
				media.setValue(data.customer.media);
			}
			
			customerMoney.setValue(data.customer.money);
			customerIntegral.setValue(data.customer.integral);
			customerRedEnvelopes.setValue(data.customer.redEnvelopes);
			
			mini.get("customer_id").setValue(data.customer.id);
			$("#keyCustomerLevel").text(data.customer.keyCustomerLevel);
			$("#back_count").text(data.customer.backCount);
			
			form1.setChanged(true);
		}, "json");
	}
	
/*-------------------------------加载省市区数据-------------------------*/
	// 弹出省份列表
 	var win1 = mini.get("win1");
 	var province = mini.get("province");
 	var provinceVal = mini.get("province_val");
 	function focusP(e) {
 		var el=e.sender.getEl();
		var bodyEl1 = win1.getBodyEl();
		$(bodyEl1).empty();
		$.post("customer_manage_find_province.do", {}, function(data) {
			win1.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl1).append("</li><a href='javascript:loadC("+obj.id+", "+'"'+obj.pName+'"'+")' style='padding: 5px;'>"+obj.pName+"</a>");
			});
		}, "json");
		
 	}
 
 	// 通过省加载城市
 	var city = mini.get("city");
 	var cityVal = mini.get("city_val");
 	var win2 = mini.get("win2");
 	function loadC(p_id, p_name) {
 		var el = city.getEl();
		var bodyEl2 = win2.getBodyEl();
		$(bodyEl2).empty();
		$.post("customer_manage_find_city.do", {provinceId: p_id}, function(data) {
	 		provinceVal.setValue(p_id);
	 		province.setValue(p_name);
	 		win1.hide();
			win2.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl2).append("<a href='javascript:loadD("+'"'+obj.id+'"'+", "+'"'+obj.cName+'"'+", "+'"'+obj.zipCode+'"'+")' style='padding: 5px;'>"+obj.cName+"</a>");
				mini.parse();
			});
		}, "json");
 	}
 	
 	// 通过城市加载区县
 	var win3 = mini.get("win3");
 	var district = mini.get("district");
 	var districtVal = mini.get("district_val");
 	var zipCode = mini.getbyName("zipCode");
 	function loadD(c_id, c_name, c_zipCode) {
 		var el = district.getEl();
 		var bodyEl3 = win3.getBodyEl();
 		zipCode.setValue(c_zipCode);
 		$(bodyEl3).empty();
 		$.post("customer_manage_find_district.do", {cityId: c_id}, function(data) {
 			city.setValue(c_name);
 			cityVal.setValue(c_id);
 			win2.hide();
 			win3.showAtEl(el, {
 			   xAlign:"left",
 			   yAlign:"below"
 			});
 			$.each(data, function(i, obj) {
				$(bodyEl3).append("<a href='javascript:setD("+obj.id+", "+'"'+obj.dName+'"'+")' style='padding: 5px;'>"+obj.dName+"</a>");
				mini.parse();
			});
 		}, "json");
 	}
 	
 	// 设置区县
 	function setD(d_id, d_name) {
 		win3.hide();
 		districtVal.setValue(d_id);
 		district.setValue(d_name);
 	}
 	
/*----订单产品信息----------------------------------------------------------------------------------------------------------*/
 	
 	//客户级别变化
 	var customerLevel = mini.get("customer_level");
 	function levelChanged() {
 		$.post("customer_edit_level.do", {customerLevel: customerLevel.getValue(), id: mini.getbyName("customerId").getValue()});
 	}
 	
 	// 运费变化,设置实收金额
 	function freightChange() {
 		ordersFreight.validate();
 		if(ordersFreight.isValid() == false) return;
 		
 		if(ordersId.getValue().length > 0) {
 			if(grid.getData().length > 0) {
		 		amountPaid.setValue(numAdd(ordersReceivable.getValue(), ordersFreight.getValue()));
		 		amountPaidChange();
 			} else {
 				mini.alert("请先添加产品！");
 				ordersFreight.setValue(0);
 			}
 		} else {
 			mini.alert("请先保存订单信息。");
 			ordersFreight.setValue(0);
 		}
 	}
 	
 	// 应收金额获取焦点时获得当前应收金额值
 	var oriReceivable = 0;
 	function getReceivable() {
 		ordersReceivable.validate();
 		if(ordersReceivable.isValid() == false) return;
 		oriReceivable = ordersReceivable.getValue();
 	}
 	
 	// 应收金额改变时触发
 	function receivableChange() {
 		ordersReceivable.validate();
 		if(ordersReceivable.isValid() == false) return;
 		if(ordersId.getValue().length > 0) {
 			if(grid.getData().length > 0) {
 				ordersPoints.setValue(ordersReceivable.getValue().toString().split(".")[0]);					// 本单积分（应收金额取整）
		 		amountPaid.setValue(numAdd(ordersReceivable.getValue(), ordersFreight.getValue()));
		 		amountPaidChange();
		 		calcDiscount();
 			} else {
 				mini.alert("请先添加产品！");
 				ordersReceivable.setValue(0);
 			}
 		} else {
 			mini.alert("请先保存订单信息。");
 			ordersReceivable.setValue(0);
 		}
 	}
 	
 	// 实收金额修改时设置积分	
 	var amountPaid = mini.get("amount_paid");			// 实收金额
 	var ordersPoints = mini.get("orders_points");		// 本单积分
 	var useMoney = mini.get("use_money");				// 使用余额
 	function amountPaidChange() {
 		amountPaid.validate();
 		if(amountPaid.isValid() == false) return;
		var or = numAdd(ordersReceivable.getValue(), ordersFreight.getValue());	// 应收金额 + 运费
		var op = amountPaid.getValue();			// 实收金额
		if(ordersId.getValue().length > 0) {
			if(grid.getData().length > 0) {
				if(amountPaidEvent() == false) return;
	 			
	 			if(Number(or) > Number(op)) {											// 应收金额 + 运费  > 实收金额时
	 				if(Number(useMoney.getValue()) != 0) {
	 					customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));  // 客户余额先加回原来使用余额
	 				}
	  				var um = numSub(or, op);											// 使用余额 = （应收金额+运费） - 实收金额
	 				useMoney.setValue(um);
	 				customerMoney.setValue(numSub(customerMoney.getValue(), um)); 		// 客户余额再减去当前使用余额
	 				this.saveAmountPaidChange();
	 			} else {							// 应收金额 + 运费  < 实收金额
	 				customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));	// 客户余额 + 使用余额
	 				useMoney.setValue(0);
	 				saveAmountPaidChange();
	 			}
			} else {
				mini.alert("请先添加产品！");
				amountPaid.setValue(0);
			}
 		} else {
 			mini.alert("请先保存订单信息!");
 			amountPaid.setValue(0);
 		}
 	}
 	
 	// 判断实收金额和客户余额之和是否大于应收金额+运费
 	function amountPaidEvent() {
		var or = numAdd(ordersReceivable.getValue(), ordersFreight.getValue());	// 应收金额 +运费
		var ap = numAdd(amountPaid.getValue(), customerMoney.getValue());		// 实收金额 + 余额
		var uap = numAdd(ap, useMoney.getValue());								// 再加上使用余额
		
 		if(Number(or) > Number(uap)) {
 			mini.alert("实收金额与客户余额之和不能小于应收金额与运费之和！");
 			return false;
 		} else {											// 应收金额 + 运费  < 实收 + 余额 + 使用余额
 			return true;
 		}
 	}
 	
 	// 保存实收金额改变
 	function saveAmountPaidChange() {
 		var o = form1.getData(true);
 		$.ajax({
	        url: "orders_edit_save.do?id=" + ordersId.getValue(),
			type: 'post',
			dataType: 'json',
	        data: o,
	        cache: false,
	    });
 	}
 	
 	// 计算产品折扣价
 	function calcDiscount() {
 		if(oriReceivable != 0) {
	 		orVal = ordersReceivable.getValue();
			$.post("orders_edit_calc_discount.do", {id: ordersId.getValue(), receivable: orVal, oriReceivable: oriReceivable}, function(data) {
				if(data.success) {
					grid.reload();
				}
			}, "json");
 		} else {
 			mini.alert("产品实际价格不能为0，请修改！");
 		}
 	}
 	
 // 红包获得焦点时触发
 	var originalRed = 0;
 	function getRed() {
 		red.validate();
		if(red.isValid() == false) return;
		originalRed = red.getValue();
 	}
 	
 	// 本单红包更改时添加到剩余红包中
 	var red = mini.get("red");
 	function redChange() {
 		// 先减去原来的红包，再加上当前红包。
		red.validate();
		if(red.isValid() == false) return;
 		if(ordersId.getValue().length > 0) {
	 		customerRedEnvelopes.setValue(numSub(customerRedEnvelopes.getValue(), originalRed));
	 		customerRedEnvelopes.setValue(numAdd(customerRedEnvelopes.getValue(), red.getValue()));
	 		saveAmountPaidChange();
 		} else {
 			mini.alert("请先保存订单信息。");
 			red.setValue(0);
 		}
 	}
 	
 	// 负数验证
	mini.VTypes["negativeErrorText"] = "不能为负数";
    mini.VTypes["negative"] = function (v) {
    	if(Number(v) < 0) {
    		return false;
    	} else {
    		return true;
    	}
    }
 	
	// 保存订单基本信息
    function onOk(e) {
    	var o = form1.getData(true); 
	    form1.validate();
	    if (form1.isValid() == false || amountPaidEvent() == false) return;
	    if(form1.isChanged()) {
	    	if(ordersId.getValue().length > 0) {
		    	$.ajax({
			        url: "orders_edit_save.do?id=" + ordersId.getValue(),
					type: 'post',
					dataType: 'json',
			        data: o,
			        cache: false,
			        success: function (text) {
			            if(text.success){
			            	mini.alert("基本信息修改成功");
			            }else{
			            	mini.alert("数据错误！");
			            }
			            form1.setChanged(false);
			        },
			        error: function (jqXHR, textStatus, errorThrown) {
			            alert(jqXHR.responseText);
			            window.CloseOwnerWindow();
			        }
			    });
		    } else {
			    $.ajax({
			        url: "orders_save.do",
					type: 'post',
					dataType: 'json',
			        data: o,
			        cache: false,
			        success: function (text) {
			            if(text.success){
			            	mini.alert("基本信息保存成功，请添加产品");
			            	ordersId.setValue(text.ordersId);
			            }else{
			            	mini.alert("数据错误！");
			            }
			            form1.setChanged(false);
			        },
			        error: function (jqXHR, textStatus, errorThrown) {
			            alert(jqXHR.responseText);
			            window.CloseOwnerWindow();
			        }
			    });
		    }
	    } else {
	    	mini.alert("订单信息未改变");
	    }
    }
 	
/*-------------订单产品--------------------------------*/
	
 	var form2 = new mini.Form("form2");
 	var grid = mini.get("datagrid1");
 	var ordersId = mini.get("orders_id");
 	grid.load({ordersId: ordersId.getValue() });
	
	var ordersReceivable = mini.get("orders_receivable"); 	// 应收金额
   	var ordersPayment = mini.get("orders_payment");			// 货款
   	var ordersFreight = mini.get("orders_freight");			// 运费
   	var ordersUsePoints = mini.get("orders_use_points");	// 本单使用积分
   	var ordersUseRed = mini.get("orders_use_red");			// 本单使用红包
 	
 	var price = mini.get("price");
 	var prePrice = mini.get("pre_price");
 	var inventory = mini.get("inventory");
 	// 弹出选择产品
 	function onButtonEdit(e) {
 		if(ordersId.getValue().length == 0) {
 			mini.alert("请先保存订单信息。");
 			return;
 		}
        var btnEdit = this;
        mini.open({
            url: "orders_product_select.do",
            title: "选择产品/赠品",
            width: 500,
            height: 350,
            allowResize: false,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { ordersId: ordersId.getValue() };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
                //if (action == "close") return false;
                if (action == "ok") {
                    var iframe = this.getIFrameEl();
                    var data = iframe.contentWindow.GetData();
                    data = mini.clone(data);
                    if (data) {
                    	inventory.setValue(data.inventory);
                        btnEdit.setValue(data.id);
                        btnEdit.setText(data.name);
                        prePrice.setValue(data.price);
                    	price.setValue(data.price);
                    }
                }
            }
        });            
    }

/*--------计算-------------------------------------------------------------------------*/
 	
 // 加法
 	function numAdd(num1, num2) {
	    var baseNum, baseNum1, baseNum2;
	    try {
	        baseNum1 = num1.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum1 = 0;
	    }
	    try {
	        baseNum2 = num2.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum2 = 0;
	    }
	    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	    return (num1 * baseNum + num2 * baseNum) / baseNum;
	};
	
	// 减法
	function numSub(num1, num2) {
	    var baseNum, baseNum1, baseNum2;
	    var precision;// 精度
	    try {
	        baseNum1 = num1.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum1 = 0;
	    }
	    try {
	        baseNum2 = num2.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum2 = 0;
	    }
	    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
	    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
	};
	
	// 乘法
	function numMulti(num1, num2) {
	    var baseNum = 0;
	    try {
	        baseNum += num1.toString().split(".")[1].length;
	    } catch (e) {
	    }
	    try {
	        baseNum += num2.toString().split(".")[1].length;
	    } catch (e) {
	    }
	    return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
	};
	
	// 积分、红包抵扣验证
	var usePoints = mini.get("use_points");
	function usePointsValid() {
		usePoints.validate();
 		if(usePoints.isValid() == false) return;
		var el = document.getElementById("use_points_error");
		if(Number(usePoints.getValue()) > Number(customerIntegral.getValue())) {
			el.innerHTML = "不能超过用户现有积分";
			return false;
		} else {
			el.innerHTML = "";
			return true;
		}
	}
	
	var useRed = mini.get("use_red");
	function useRedValid() {
		useRed.validate();
 		if(useRed.isValid() == false) return;
		var el = document.getElementById("use_red_error");
		if(Number(useRed.getValue()) > Number(customerRedEnvelopes.getValue())) {
			el.innerHTML = "不能超过用户现有红包";
			return false;
		} else {
			el.innerHTML = "";
			return true;
		}
	}
   	
   	// 比较添加的产品，积分和红包总和与价格的大小
   	var quantity = mini.getbyName("quantity");
   	function compare() {
   		var productPrice = numMulti(prePrice.getValue(), quantity.getValue());
   		var redAndPoints = numAdd(usePoints.getValue(), useRed.getValue());
   		if(productPrice >= redAndPoints) {
   			return true;
   		} else {
   			mini.alert("使用红包和积分总和不能大于总价格！");
   			return false;
   		}
   	}
 	
   	// 保存产品
 	function onOk2() {
 		var o = form2.getData(true); 
	    form2.validate();
	    if (form2.isValid() == false || usePointsValid() == false || useRedValid() == false || compare() == false) return;
	    if(ordersId.getValue().length > 0 ) {
		  	if(quantity.getValue() > inventory.getValue()) {
		  		mini.confirm("该产品库存量不足，确定继续购买？", "产品库存不足提示",
		            function (action) {
		                if (action == "ok") {
		                	productSave(o);
		                }
		            }
			    );
		  	} else {
		  		productSave(o);
		  	}
	    }else {
	    	mini.alert("请先保存订单基本信息！");
	    }
 	}
   	
   	// 保存产品信息
   	function productSave(o) {
   		form2.loading();
   		$.ajax({
	        url: "orders_product_save.do?ordersId=" + ordersId.getValue(),
			type: 'post',
			dataType: 'json',
	        data: o,
	        cache: false,
	        success: function (text) {
	            if(text.success){
	            	grid.load({ordersId: ordersId.getValue() });
	            	var price = numMulti(o.price, o.quantity);				// 单个产品货款 = 价格*数量
	            	var prePrice = numMulti(o.prePrice, o.quantity);		// 单个产品优惠金额 = 优惠价格*数量
	            	var redAndPoint = numAdd(o.usePoints, o.useRed);
	            	var singleAmountPaid = numSub(prePrice, redAndPoint);	// 单个产品实际价格 = 优惠价格-积分/红包抵扣
	            	var prePrice1 = numSub(prePrice, redAndPoint);			// 单个产品应收 = 优惠  - 积分 -红包
	            	var pf = numAdd(singleAmountPaid, o.freight);			// 单品实收金额 = 实际价格+运费
	            	
	            	ordersPayment.setValue(numAdd(ordersPayment.getValue(), price));				// 订单货款
	            	ordersFreight.setValue(numAdd(ordersFreight.getValue(), o.freight));			// 订单运费
	            	ordersReceivable.setValue(numAdd(ordersReceivable.getValue(), prePrice1));		// 订单应收金额
	            	amountPaid.setValue(numAdd(amountPaid.getValue(), pf));							// 订单实收金额
	            	ordersUsePoints.setValue(numAdd(ordersUsePoints.getValue(), o.usePoints));		// 订单使用积分
	            	
	            	var thisOrdersPoints = ordersReceivable.getValue().toString().split(".")[0];
	            	ordersPoints.setValue(thisOrdersPoints);											// 本单积分(应收金额取整)
	            	
	            	ordersUseRed.setValue(numAdd(ordersUseRed.getValue(), o.useRed));					// 订单使用红包
	            	
	            	customerIntegral.setValue(numSub(customerIntegral.getValue(), usePoints.getValue()));			// 剩余积分设值
	            	customerRedEnvelopes.setValue(numSub(customerRedEnvelopes.getValue(), useRed.getValue()));		// 剩余红包设值
	            	
	            	var o1 = form1.getData(true);
	            	o1.integral = customerIntegral.getValue();
	            	o1.redEnvelopes = customerRedEnvelopes.getValue();
	            	$.ajax({
	    		        url: "orders_edit_save.do?id=" + ordersId.getValue(),
	    				type: 'post',
	    				dataType: 'json',
	    		        data: o1,
	    		        cache: false,
	    		        success: function (text) {
	    		            if(text.success){
	    		            	form2.reset();
	    		            	form2.unmask();
	    		            }
	    		        },
	    		    });
	            }else{
	            	mini.alert("数据错误(订单id不能为空)！");
	            }
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	            alert(jqXHR.responseText);
	            window.CloseOwnerWindow();
	        }
	    });
   	}
 	
 	// 删除订单产品
 	function onActionRenderer() {
 		return '<a style="width:150px;" href="javascript:del()">删除</a>';
 	}
 	
 	function del() {
 		var row = grid.getSelected();
 	    if (row) {
 	    	$.ajax({
                url: "orders_product_del.do?id=" + row.id,
                dataType: "json",
                success: function (text) {
               		if(text.success) {
               			grid.reload();
               			
               			ordersPayment.setValue(numSub(ordersPayment.getValue(), numMulti(row.price, row.quantity)));	// 删除减去货款
               			ordersFreight.setValue(numSub(ordersFreight.getValue(), row.freight));				// 删除减去运费
               			ordersReceivable.setValue(numSub(ordersReceivable.getValue(), row.discountPrice));	// 删除减去应收金额
               			
               			if(grid.getData().length-1 == 0){														// 产品为0是，设置应收为0
               				ordersReceivable.setValue(0);
               				ordersFreight.setValue(0);
               			}
               			
               			var apUm = numAdd(amountPaid.getValue(), useMoney.getValue());						// 实收金额+使用余额
               			if(ordersReceivable.getValue() == 0) {												// 应收金额为0了，实收也必须为0
               				amountPaid.setValue(0);
               			} else {
	               			amountPaid.setValue(numSub(apUm, row.discountPrice));								// 删除时产品计算实收金额
               			}
               			
               			customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));		// 设置剩余余额
               			useMoney.setValue(0);																// 设置使用余额
               			
               			ordersPoints.setValue(ordersReceivable.getValue().toString().split(".")[0]);		// 删除产品本单积分（应收金额取整）
               			ordersUsePoints.setValue(numSub(ordersUsePoints.getValue(), row.usePoints));		// 本单使用积分-产品用积分
               			ordersUseRed.setValue(numSub(ordersUseRed.getValue(), row.useRed));					// 本单使用红包-产品用红包
               			customerIntegral.setValue(numAdd(customerIntegral.getValue(), row.usePoints));		// 剩余积分
               			customerRedEnvelopes.setValue(numAdd(customerRedEnvelopes.getValue(), row.useRed));	// 剩余红包
                        var o1 = form1.getData(true);
                        o1.integral = customerIntegral.getValue();
    	            	o1.redEnvelopes = customerRedEnvelopes.getValue();
                        $.ajax({
    	    		        url: "orders_edit_save.do?id=" + ordersId.getValue(),
    	    				type: 'post',
    	    				dataType: 'json',
    	    		        data: o1,
    	    		        cache: false,
    	    		        success: function (text) {
    	    		            if(text.success){
    	    		            	
    	    		            }
    	    		        },
    	    		    });
   		            } else {
   		            	mini.alert("数据错误(id不能为空)！");
   		            }
                }
            });
 	    } else {
 	        mini.alert("请选中一条记录");
 	    }
 	}
    
    function onCancel(e) {
    	window.CloseOwnerWindow("cancel");
    }
    
    function onOk3() {
    	if(grid.getData().length == 0) {
    		mini.alert("订单未选择任何产品，不能生效！");
    	} else {
    		if(amountPaidEvent() == false) return;
	    	$.post("orders_edit_status.do", {id: ordersId.getValue()}, function(data) {
	    		if(data.success) {
	    			window.CloseOwnerWindow("succ");
	    		}
	    	}, "json");
    	}
    }
    
/*连接WebSocket*/
    jQuery.openWebSocket("ws://172.16.2.11:8080/websocket");
    
// 连接成功时执行
    function webSocketOnOpen(event) {
		
 	}
    
    // 呼出电话
   	var winOutgoing = mini.get("win—outgoing");
    var outNumId = mini.get("outNumId");
    var addNum = mini.get("addNum");
    
    function outgoing1() {
		winOutgoing.showAtPos("right", "top");
		outNumId.setValue(contactNo.getValue());
    }
    
    function outgoing2() {
		winOutgoing.showAtPos("right", "top");
		outNumId.setValue(contactNos.getValue());
    }
    
    function outgoingOk() {
    	$.post("alternately_cur_extension.do", function(data) {
    		if(null != data.phoneNum && 0 != data.phoneNum && data.phoneNum.length > 0) {
    			var arr = new Array();
    			arr[0] = addNum.getValue();
    			arr[1] = outNumId.getValue();
    			var callNum = arr.join("");
    			jQuery.dail(data.phoneNum, callNum);
    			winOutgoing.hide();
    			outNumId.setValue("");
    			addNum.setValue("");
    		} else {
    			mini.alert("未登录分机");
    		}
    	}, "json")
    }
    
    function onClose2() {
    	winOutgoing.hide();
    	outNumId.setValue("");
    	addNum.setValue("");
    } 
    
   	// 验证号码格式
   	mini.VTypes["numTypeErrorText"] = "号码格式不正确";
    mini.VTypes["numType"] = function (v) {
    	if(v.length > 0) {
	    	var reMobile = new RegExp("^0?1[34578]\\d{9}$");
	    	var rePhone = new RegExp("^(010|02\\d|0[3-9]\\d{2})?\\d{7,8}$");
	    	if(reMobile.test(v)) {
	    		return true;
	    	} else if(rePhone.test(v)) {
	    		return true;
	    	} else {
	    		return false;
	    	}
    	} else {
    		return true;
    	}
    }
</script>